package wifiunion.com.notice.fragment;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;

import wifiunion.com.notice.BaseFragment;
import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.MyNoticeListener;
import wifiunion.com.notice.NoticeContact;
import wifiunion.com.notice.R;
import wifiunion.com.notice.entity.NoticeInfoList;
import wifiunion.com.notice.presenter.AddNoticeDataPresenter;
import wifiunion.com.notice.utils.ClickTimeSpanUtil;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.utils.db.DBManager;
import wifiunion.com.notice.utils.db.LocNoticeInfo;
import wifiunion.com.notice.widget.AddNoticeGroupDialog;

/**
 * Created by Administrator on 2016/11/28.
 * 添加通知内容
 */

public class AddNoticeDataFragment extends BaseFragment implements View.OnClickListener, NoticeContact.View {

    private View mMainView;
    private int pageType;
    private String noticeUuid;
    private TextView headDowntv;
    private TextView headUpTv;
    private String mAuthtoken;
    private RadioGroup optRG;
    private RadioButton unlimitedRB;
    private RadioButton onlyOneRB;
    private int rate;

    private RadioGroup soudRG;
    private RadioButton systemdefRB;
    private RadioButton selfRB;
    private int soudtype;

    private RelativeLayout chooseRl;
    private TextView chooseTv;
    private TextView choooseAddTv;


    private EditText dataEt;
    private AddNoticeDataPresenter mAddNoticeDataPresenter;

    private ImageView ovaltznrIv;
    private TextView titletznrTv;

    private AddNoticeGroupDialog mAddNoticeGroupDialog;

    private NoticeInfoList mNoticeInfoList;
    private static final int MAX_COUNT = 60;

    private TextView sizeTv;

    private Fragment mFragment;

    private String path;

    /**
     * 自定义通知频次的输入框
     */
    private EditText mFrequencyEdt;
    /**
     *
     */
    private CheckBox showNoticeTimeCb;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMainView = inflater.inflate(R.layout.fragment_addnoticedata, container, false);
        Bundle bundle = getArguments();
        if (null != bundle) {
            pageType = bundle.getInt("pageType");
            if (pageType == 0) {
                noticeUuid = bundle.getString("noticeUuid");
            } else if (pageType == 1 || pageType == 2) {
                mNoticeInfoList = (NoticeInfoList) bundle.getSerializable("notice");
                noticeUuid = mNoticeInfoList.getUuid();
            }
        }
        mFragment = this;

        mAuthtoken = SharedPreferencesUtils.getSharedPreferences(Constants.CONFIG_AUTHTOKEN, getActivity());
        initview();
        return mMainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mAddNoticeDataPresenter = new AddNoticeDataPresenter(getContext(), this);


    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
//                    getFragmentManager().popBackStack();
                    getActivity().getSupportFragmentManager().popBackStack();
                    return true;
                }
                return false;
            }
        });
    }


    @Override
    public void initview() {

        ovaltznrIv = (ImageView) mMainView.findViewById(R.id.oval_tznr_iv);
        ovaltznrIv.setBackgroundResource(R.drawable.notice_mark_material_select);
        titletznrTv = (TextView) mMainView.findViewById(R.id.title_tznr_tv);

        headDowntv = (TextView) mMainView.findViewById(R.id.notice_head_down_tv);
        if (pageType == 0 || pageType == 2) {
            headDowntv.setText("保存");
        } else {
            headDowntv.setText("返回");
        }

        headDowntv.setOnClickListener(this);
        headUpTv = (TextView) mMainView.findViewById(R.id.notice_head_up_tv);
        headUpTv.setOnClickListener(this);

        sizeTv = (TextView) mMainView.findViewById(R.id.zhengwen_size_tv);


        dataEt = (EditText) mMainView.findViewById(R.id.notice_data_et);
        dataEt.addTextChangedListener(mTextWatcher);
        optRG = (RadioGroup) mMainView.findViewById(R.id.sendtype_rg);
        unlimitedRB = (RadioButton) mMainView.findViewById(R.id.everytime_rb);
        onlyOneRB = (RadioButton) mMainView.findViewById(R.id.onlyone_rb);
        unlimitedRB.setChecked(true);
        optRG.setOnCheckedChangeListener(mylistener);
        mFrequencyEdt = (EditText) mMainView.findViewById(R.id.notice_frequency_edt);

        soudRG = (RadioGroup) mMainView.findViewById(R.id.sound_rg);
        systemdefRB = (RadioButton) mMainView.findViewById(R.id.system_def);
        selfRB = (RadioButton) mMainView.findViewById(R.id.self);
        systemdefRB.setChecked(true);
        soudRG.setOnCheckedChangeListener(soudlistener);

        chooseRl = (RelativeLayout) mMainView.findViewById(R.id.notice_choose_rl);
        chooseTv = (TextView) mMainView.findViewById(R.id.notice_choose_tv);
        choooseAddTv = (TextView) mMainView.findViewById(R.id.notice_chooseadd_tv);
        choooseAddTv.setOnClickListener(this);

        showNoticeTimeCb = (CheckBox) mMainView.findViewById(R.id.show_noticetime_cb);

        if (pageType == 0) {
            headDowntv.setEnabled(true);
            systemdefRB.setChecked(true);
            mFrequencyEdt.setEnabled(true);
            showNoticeTimeCb.setEnabled(true);
        } else if (pageType == 1) {
            optRG.setEnabled(false);
            unlimitedRB.setEnabled(false);
            onlyOneRB.setEnabled(false);
            mFrequencyEdt.setEnabled(false);
            showNoticeTimeCb.setEnabled(false);

            if(mNoticeInfoList.getIsShowTime()==0)
            {
                showNoticeTimeCb.setChecked(false);
            }
            else
            {
                showNoticeTimeCb.setChecked(true);
            }
//            if (mNoticeInfoList.getRate() == 0) {
//                unlimitedRB.setChecked(true);
//            } else {
//                onlyOneRB.setChecked(true);
//            }

            if (mNoticeInfoList.getRate() == 0) {
                unlimitedRB.setChecked(true);
                rate = 0;
                mFrequencyEdt.setText("0");
            } else {
                onlyOneRB.setChecked(true);
                rate = mNoticeInfoList.getRate();
                mFrequencyEdt.setText(String.valueOf(mNoticeInfoList.getRate()));
            }





            soudRG.setEnabled(false);
            systemdefRB.setEnabled(false);
            selfRB.setEnabled(false);
            LocNoticeInfo info = DBManager.getInstance(getContext()).findLocNoticeInfoByUuid(noticeUuid);
            if (null != info) {
                if (info.getSoundType() == 0) {
                    systemdefRB.setChecked(true);


                } else if (info.getSoundType() == 1) {
                    selfRB.setChecked(true);
                    chooseTv.setText(info.getSoundUrl());
                }


            } else {
                //本地数据库不存在时，默认选中系统
                systemdefRB.setChecked(true);
                selfRB.setChecked(false);
            }

            choooseAddTv.setEnabled(false);

//            if (mNoticeInfoList.getRate() == 0) {
//                unlimitedRB.setChecked(true);
//            } else {
//                onlyOneRB.setChecked(true);
//            }


            dataEt.setEnabled(false);
            if (null != mNoticeInfoList.getContent() && mNoticeInfoList.getContent().length() > 0) {
                try {
                    dataEt.setText(URLDecoder.decode(mNoticeInfoList.getContent(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    dataEt.setText("");
                    e.printStackTrace();
                }
            }


        } else if (pageType == 2) {
            headDowntv.setEnabled(true);

            optRG.setEnabled(true);
            unlimitedRB.setEnabled(true);
            onlyOneRB.setEnabled(true);
            mFrequencyEdt.setEnabled(true);
            showNoticeTimeCb.setEnabled(true);

            if(mNoticeInfoList.getIsShowTime()==0)
            {
                showNoticeTimeCb.setChecked(false);
            }
            else
            {
                showNoticeTimeCb.setChecked(true);
            }


            if (mNoticeInfoList.getRate() == 0) {
                unlimitedRB.setChecked(true);
                rate = 0;
                mFrequencyEdt.setText("0");
            } else {
                onlyOneRB.setChecked(true);
                rate = mNoticeInfoList.getRate();
                mFrequencyEdt.setText(String.valueOf(mNoticeInfoList.getRate()));
            }

            soudRG.setEnabled(true);
            systemdefRB.setEnabled(true);
            selfRB.setEnabled(true);
            LocNoticeInfo info = DBManager.getInstance(getContext()).findLocNoticeInfoByUuid(noticeUuid);
            if (null != info) {
                if (info.getSoundType() == 0) {
                    systemdefRB.setChecked(true);
                    soudtype = 0;


                } else if (info.getSoundType() == 1) {
                    selfRB.setChecked(true);
                    chooseTv.setText(info.getSoundUrl());
                    soudtype = 1;
                }

            } else {
                systemdefRB.setChecked(true);
                soudtype = 0;

            }
            choooseAddTv.setEnabled(true);


            dataEt.setEnabled(true);
            if (null != mNoticeInfoList.getContent() && mNoticeInfoList.getContent().length() > 0) {

                try {
                    dataEt.setText(URLDecoder.decode(mNoticeInfoList.getContent(), "utf-8"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }




        }


    }

    RadioGroup.OnCheckedChangeListener mylistener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup Group, int checkedId) {

            if (checkedId == unlimitedRB.getId()) {

                rate = 0;
            } else if (checkedId == onlyOneRB.getId()) {
                rate = 1;
            } else {
                rate = 0;
            }


        }
    };


    RadioGroup.OnCheckedChangeListener soudlistener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup Group, int checkedId) {

            if (checkedId == systemdefRB.getId()) {

                soudtype = 0;
            } else if (checkedId == selfRB.getId()) {
                soudtype = 1;
            } else {
                soudtype = 0;
            }


        }
    };


    @Override
    public void initData() {

    }


    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.notice_head_down_tv) {
            if (pageType == 0 || pageType == 2) {

                if (!"".equals(dataEt.getText().toString()) && dataEt.getText().toString().length() > 0) {

                    if (soudtype == 1) {
                        if (TextUtils.isEmpty(chooseTv.getText().toString())) {
                            Toast.makeText(getContext(), "请选择音频文件", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }

                    //加载子菜单
                    HashMap<String, Object> params = new HashMap<>();
                    params.put("Authorization", mAuthtoken);
                    params.put("uuid", noticeUuid);


                    if(showNoticeTimeCb.isChecked())
                    {
                        params.put("isShowTime", 1);
                    }
                    else
                    {
                        params.put("isShowTime", 0);
                    }


                    try {
                        params.put("content", dataEt.getEditableText().toString());
                    } catch (Exception e) {
                        params.put("content", "");
                        e.printStackTrace();
                    }

                    if (rate == 0) {
                        params.put("rate", String.valueOf(rate));
                    } else {
                        String result = mFrequencyEdt.getEditableText().toString();
                        if (TextUtils.isEmpty(result)) {
                            Toast.makeText(getContext(), "请输入通知内容", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            try {
                                rate = Integer.parseInt(result);
                                params.put("rate", String.valueOf(result));
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(getContext(), "请输入通知内容", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }

                    }


                    if (ClickTimeSpanUtil.isFastDoubleClick()) {
                        return;
                    }
                    mAddNoticeDataPresenter.addNoticeData(params);
                } else {
                    Toast.makeText(getContext(), "请输入通知内容", Toast.LENGTH_SHORT).show();
                }
            } else if (pageType == 1) {
//                getFragmentManager().popBackStack();
//                getFragmentManager().popBackStack();
//                getFragmentManager().popBackStack();
//                getFragmentManager().popBackStack();
//                getFragmentManager().popBackStack();
                NoticeListFragment noticeListFragment = (NoticeListFragment) getActivity().getSupportFragmentManager().findFragmentByTag("noticeListFragment");
                if(noticeListFragment==null)
                {
                    noticeListFragment = new NoticeListFragment();
                }
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.reight_fl, noticeListFragment, "noticeListFragment").addToBackStack(null).commit();
            }


        } else if (i == R.id.notice_head_up_tv) {
            getActivity().getSupportFragmentManager().popBackStack();


        } else if (i == R.id.notice_chooseadd_tv) {//                Intent audioIntent = new Intent(Intent.ACTION_GET_CONTENT);
//                audioIntent.setType("audio/*");
//                startActivityForResult(audioIntent,100);

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("audio/*"); //选择音频
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            mFragment.startActivityForResult(intent, 100);


        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            if (requestCode == 100) {
                path = null;
                Uri uri = data.getData();
                if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
                    path = uri.getPath();

//                    Toast.makeText(this,path+"11111",Toast.LENGTH_SHORT).show();

                }

                if (TextUtils.isEmpty(path)) {

                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                        path = getPath(getContext(), uri);

//                    Toast.makeText(this,path,Toast.LENGTH_SHORT).show();
                    } else {//4.4以下下系统调用方法
                        path = getRealPathFromURI(uri);

//                    Toast.makeText(MainActivity.this, path+"222222", Toast.LENGTH_SHORT).show();
                    }
                }
//                Toast.makeText(getContext(), path, Toast.LENGTH_SHORT).show();

                if (!TextUtils.isEmpty(path)) {
                    String type = null;
                    int lastDot = path.lastIndexOf(".");
                    if (lastDot < 0) {
                        path = null;
                        chooseTv.setText("");
                        Toast.makeText(getContext(), "请选择MP3，WAV，OGG格式的音频文件!", Toast.LENGTH_SHORT).show();
                    } else {
                        type = path.substring(lastDot + 1).toUpperCase();
                    }
                    if (null != type) {
                        if ("MP3".equals(type) || "OGG".equals(type) || "WAV".equals(type)) {
                            chooseTv.setText(path);
                        } else {
                            path = null;
                            chooseTv.setText("");
                            Toast.makeText(getContext(), "请选择MP3，WAV，OGG格式的音频文件!", Toast.LENGTH_SHORT).show();
                        }
                    }
                }


            }
        }

    }

    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            ;
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
            cursor.close();
        }
        return res;
    }

    /**
     * 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
     */
    @SuppressLint("NewApi")
    public String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }


    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


    @Override
    public void onProgress() {

    }

    @Override
    public void onError(final Object obj) {
        if (obj == null) {
            Toast.makeText(getContext(), "网络异常", Toast.LENGTH_SHORT).show();
        } else {
            try {
                Toast.makeText(getContext(), (String) obj, Toast.LENGTH_SHORT).show();
            } catch (Exception e) {

            }
        }

    }

    @Override
    public void onSuccess(Object obj) {

    }

    @Override
    public void getGroupListSuccess(Object obj) {

    }

    @Override
    public void getNoticeListSuccess(Object obj) {

    }

    @Override
    public void getNotificationUserSuccess(Object obj) {

    }

    @Override
    public void getNotificationRelGroupList(Object obj) {

    }

    @Override
    public void getNoticeRelGroupMemberListSuccess(Object obj) {

    }

    @Override
    public void addNoticeSBDXSuccess(String noticeUuid) {

    }

    @Override
    public void addSBSDSuccess(Object obj) {

    }

    @Override
    public void onGetDeviceLocListSuccess(Object obj) {

    }

    @Override
    public void onGetDeviceListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeDeviceGroupListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeDeviceGroupUuidSuccess(Object obj) {

    }

    @Override
    public void addNoticeDeviceSuccess(Object obj) {

    }

    @Override
    public void getTopGroupListSuccess(Object obj) {

    }

    @Override
    public void getNoticeTargetListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeTargetRelGroupListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeTargetGroupUuidSuccess(Object obj) {

    }

    @Override
    public void addNoticeTarGetDeviceSuccess(Object obj) {

    }

    @Override
    public void addNoticeDataSuccess(Object obj) {

        //弹出选择分组的
        LocNoticeInfo info = new LocNoticeInfo();
        info.setUuid(noticeUuid);
        if (soudtype == 0) {
            info.setSoundType(0);
            info.setSoundUrl("");
        } else {
            info.setSoundType(1);
            info.setSoundUrl(chooseTv.getText().toString());
        }
        DBManager.getInstance(getContext()).saveOrupdateNotice(info);


        if (pageType == 0) {
            mAddNoticeGroupDialog = new AddNoticeGroupDialog(getContext(), getActivity(), pageType, noticeUuid, null, myListener, 0);
        } else {
            mAddNoticeGroupDialog = new AddNoticeGroupDialog(getContext(), getActivity(), pageType, noticeUuid, mNoticeInfoList.getGroupUuid(), myListener, 0);

        }

        mAddNoticeGroupDialog.setTitleMsg("选择分组");

        Log.e(Constants.TAG, "mAddNoticeGroupDialog.isShowing()  " + (mAddNoticeGroupDialog.isShowing()));
        mAddNoticeGroupDialog.show();


    }

    @Override
    public void deleteNoticeSuccess(Object obj) {

    }

    @Override
    public void addNoticeGroupSuccess(Object obj) {

    }

    @Override
    public void addNoticeRelGroupSuccess(Object obj) {

    }

    @Override
    public void setNoticeFromSuccess(Object obj) {


    }

    @Override
    public void getNoticeDetailSuccess(Object obj) {

    }

    @Override
    public void deleteNoticeGroupSuccess(Object obj) {

    }

    @Override
    public void setPresenter(BasePresenter tp) {

    }

    //回调刷行列表
    private MyNoticeListener myListener = new MyNoticeListener() {
        @Override
        public void refreshData(final String text) {

            if(getActivity()!=null)
            {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        NoticeListFragment noticeListFragment = (NoticeListFragment) getActivity().getSupportFragmentManager().findFragmentByTag("noticeListFragment");
                        if(noticeListFragment==null)
                        {
                            noticeListFragment = new NoticeListFragment();
                        }
                        getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.reight_fl, noticeListFragment, "noticeListFragment").addToBackStack(null).commit();
                    }
                });
            }


        }

        @Override
        public void refreshCancelData(final String text) {

        }

        @Override
        public void onResponse(List<Object> data) {

        }

    };

    private TextWatcher mTextWatcher = new TextWatcher() {

        private int editStart;

        private int editEnd;

        public void afterTextChanged(Editable s) {
            editStart = dataEt.getSelectionStart();
            editEnd = dataEt.getSelectionEnd();

            // 先去掉监听器，否则会出现栈溢出
            dataEt.removeTextChangedListener(mTextWatcher);

            // 注意这里只能每次都对整个EditText的内容求长度，不能对删除的单个字符求长度
            // 因为是中英文混合，单个字符而言，calculateLength函数都会返回1
            while (calculateLength(s.toString()) > MAX_COUNT) { // 当输入字符个数超过限制的大小时，进行截断操作
                s.delete(editStart - 1, editEnd);
                editStart--;
                editEnd--;
            }
            dataEt.setText(s);
            dataEt.setSelection(editStart);

            // 恢复监听器
            dataEt.addTextChangedListener(mTextWatcher);

            setLeftCount();
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
             Log.i("test","#######beforeTextChanged########");
        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            Log.i("test","#######onTextChanged########");
        }

    };

    /**
     * 计算分享内容的字数，一个汉字=两个英文字母，一个中文标点=两个英文标点 注意：该函数的不适用于对单个字符进行计算，因为单个字符四舍五入后都是1
     *
     * @param c
     * @return
     */
    private long calculateLength(CharSequence c) {
//        double len = 0;
//        for (int i = 0; i < c.length(); i++) {
//            int tmp = (int) c.charAt(i);
//            if (tmp > 0 && tmp < 127) {
//                len += 0.5;
//            } else {
//                len++;
//            }
//        }
//        return Math.round(len);

        return c.length();
    }

    /**
     * 刷新剩余输入字数,最大值新浪微博是140个字，人人网是200个字
     */
    private void setLeftCount() {
        sizeTv.setText(String.valueOf((getInputCount())) + "/60");
    }

    /**
     * 获取用户输入的分享内容字数
     *
     * @return
     */
    private long getInputCount() {
        try {


            return calculateLength(
                    dataEt.getText().toString());
        } catch (Exception e) {
            e.printStackTrace();
            return 60;
        }
    }


}
